<template>
  <div class="container">
    <div ref="searchRef">
      <el-form :inline="true" :model="formInline" class="grids gridColumns5">
        <el-form-item label="培训分类">
          <courseTypCascader v-model="formInline.type"></courseTypCascader>
        </el-form-item>
        <el-form-item label="课程名称">
          <courseQuery v-model="formInline.name" val="name"></courseQuery>
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select v-model="formInline.status" placeholder="请选择" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" plain @click="dialogVisible=true">新增</el-button>
          <el-button @click="init">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div ref="tableRef">
      <el-table :data="tableParams.rows" v-loading="tableLoading" :max-height="tableMaxHeight">
        <el-table-column prop="sort" label="序号" width="80">
          <template #default="scope">
            <el-input v-model.number="scope.row.sort" placeholder="排序" type="number" @change="inputSort(scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="培训分类" width="300">
          <template #default="scope">
            {{type_format(scope.row.type)}}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称" width="650" />
        <el-table-column prop="courseDuration" label="总计课时" width="100">
          <template #default="scope">
            <el-input v-model="scope.row.courseDuration" placeholder="总计课时" type="number" @change="inputSort(scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="课程价格" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.price" placeholder="折扣价格" type="number" @change="inputSort(scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="折扣价格" width="120">
          <template #default="scope">
            {{displayPrice_format(scope.row.lessonContent)}}
          </template>
        </el-table-column>
        <el-table-column label="上架状态" width="100" align="center">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status">上架</el-tag>
            <el-tag type="danger" v-else>下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="生效状态" width="100" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.isEffective" v-if="scope.row.hasOwnProperty('isEffective')" disabled :active-value="1" :inactive-value="0" />
            <el-switch :model-value="true" v-else disabled />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" icon="Edit" circle @click="handleEdit(scope.row, 1)" />

            <el-tooltip class="box-item" effect="dark" content="用户信息绑定" placement="top">
              <el-button type="primary" plain circle size="small" icon="Tickets" @click="proxy.$refs.courseUserInfoBindingRef.open(scope.row)"></el-button>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="课程介绍" placement="top">
              <el-button size="small" plain icon="ChatLineRound" circle @click="handleEdit(scope.row, 2)" />
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" :content="scope.row.status == 1?'下架':'上架'" placement="top">
              <el-button :type="scope.row.status == 1?'warning':'success'" circle size="small" :icon="scope.row.status == 1?'Bottom':'Top'" @click="handleEdit(scope.row, 3)"></el-button>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="小程序码" placement="top">
              <el-button type="primary" plain circle size="small" icon="loading" @click="handleEdit(scope.row, 5)"></el-button>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="网站分享链接" placement="top">
              <el-button type="primary" plain circle size="small" icon="link" @click="handleEdit(scope.row, 6)"></el-button>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="网站分享二维码" placement="top">
              <el-button type="primary" plain circle size="small" icon="camera" @click="handleEdit(scope.row, 7)"></el-button>
            </el-tooltip>

            <el-button type="danger" size="small" icon="Delete" circle @click="handleEdit(scope.row, 4)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Pagination v-if="tableParams['total']" :total="tableParams['total']" v-model:page="formInline.pageIndex" v-model:limit="formInline.pageSize" @pagination="getInfo" />

    <el-dialog v-model="dialogVisible" :title="`新增/编辑 - ${model.name}`" width="80%" :before-close="handleClose">
      <el-form :model="model" label-width="80px" :rules="rules" ref="formRef" label-position="top">
        <div v-if="showIntro">
          <el-form-item label="课程介绍" prop="intro">
            <Editor v-model="model.intro" :minHeight="600"></Editor>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="分类" prop="type">
            <courseTypCascader v-model="model.type"></courseTypCascader>
          </el-form-item>
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="model.name" placeholder="课程名称" clearable />
          </el-form-item>
          <el-form-item label="课程价格" prop="price">
            <el-input v-model="model.price" placeholder="课程价格" clearable type="number" />
          </el-form-item>
          <el-form-item label="课程折扣">
            <el-input :value="displayPrice_format(model.lessonContent)" placeholder="课程折扣" clearable disabled />
          </el-form-item>
          <el-form-item label="商品图片" prop="coverUrl">
            <div>
              <div class="actionBtn flex alignCenter">
                <el-button type="primary" plain @click="proxy.$refs.uploadImageCom.inputClick()">新增</el-button>
                （建议尺寸1920*1080）
              </div>
              <div class="flex flexWrap">
                <div class="bannerBox" @click="proxy.$refs.uploadImageCom.showPreview(item)" v-for="(item, index) in model.coverUrl" :key="index">
                  <img :src="item" alt="" srcset="">
                  <div class="iconDel" @click.stop="model.coverUrl.splice(index, 1)">
                    <el-icon color="#fff">
                      <Close />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="课程内容">
            <lessonContent v-model="model.lessonContent"></lessonContent>
            <div class="flex alignCenter" style="margin-top: 10px">
              请选择
              <el-input style="width: 80px; margin:0 10px" v-model.number="model.lessonContentMin" placeholder="请输入最小课时数量" clearable type="number" />
              门课程
            </div>
          </el-form-item>
          <el-form-item label="开票时间">
            <div>
              <datePickerRange v-model:start="model.invoiceStart" v-model:end="model.invoiceEnd">
              </datePickerRange>
            </div>
          </el-form-item>
          <el-form-item label="咨询电话">
            <dictSelect dictCode="enterprise_user" v-model="model.consultingPhone" multiple="1"></dictSelect>
          </el-form-item>
          <el-form-item label="联系二维码">
            <uploadImage v-model="model.contactQrCode"></uploadImage>
          </el-form-item>
          <el-form-item label="学员来源">
            <dictSelect dictCode="user_source" v-model="model.studentSource"></dictSelect>
          </el-form-item>
          <el-form-item label="总计课时">
            <el-input v-model="model.courseDuration" placeholder="请输入总计课时" clearable type="number" />
          </el-form-item>
          <el-form-item label="上架状态">
            <el-select v-model="model.status" placeholder="请选择">
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="生效状态">
            <el-switch v-model="model.isEffective" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="是否不校验报名次数">
            <el-switch v-model="model.verifyRegistrations" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="新增标签">
            <div class="actionBtn" @click="model.navs.push({ name: '', path: '' ,color:''})">
              <el-button type="primary" plain>新增</el-button>
            </div>
            <div class="grids gridColumns5" style="margin-bottom:10px;gap: 15px 15px" v-for="(item, index) in model.navs" :key="index">
              <el-input v-model="item.name" placeholder="请输入导航栏标题" />
              <el-input v-model="item.path" placeholder="请输入超链接" />
              <el-color-picker v-model="item.color" />
              <el-button type="danger" icon="Delete" circle @click="model.navs.splice(index, 1)" />
            </div>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="model.sort" placeholder="排序" clearable type="number" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <uploadImage ref="uploadImageCom" v-show="false" v-model="coverUrl"></uploadImage>

    <courseUserInfoBinding ref="courseUserInfoBindingRef"></courseUserInfoBinding>

    <courseQrCode ref="courseQrCodeRef"></courseQrCode>
  </div>
</template>

<script setup lang="ts">
//分享二维码
import courseQrCode from "@/views/websiteConfiguration/components/courseQrCode.vue";
// 课堂内容
import lessonContent from "@/views/websiteConfiguration/components/lessonContent.vue";
import courseUserInfoBinding from "@/views/websiteConfiguration/components/courseUserInfoBinding.vue";
const { proxy } = getCurrentInstance();
//counter
import useCounterStore from "@/store/counter";
const instance = getCurrentInstance();

const counter = useCounterStore();

let formInline = ref({
  pageIndex: 1,
  pageSize: 50,
  name: "",
  type: "",
  status: "",
});

let model = ref({
  name: "",
  price: "",
  coverUrl: [],
  contactQrCode: "", //联系二维码
  invoiceStart: null, //开票开始时间
  invoiceEnd: null, //开票结束时间
  intro: "", //富文本
  sort: 0,
  type: "", //分类
  lessonContent: [], //课程内容
  status: 1, //状态  //1 上架
  lessonContentMin: 1, //课时内容选择数量区间
  lessonContentMax: 1, //课时内容选择数量区间
  newPrice: null,
  courseDuration: null,
  consultingPhone: "", //咨询电话
  studentSource: "", //学员来源
  isEffective: 1, //是否有效
  navs: [],
  verifyRegistrations: 0, //是否校验报名次数
});
let coverUrl = ref(""); //封面图片

let tableParams = ref({});
let dialogVisible = ref(false);
let loading = ref(false);
let tableLoading = ref(false);
let showIntro = ref(false);
let tableData = ref([]); //数组
let courseType = []; //分类列表
let searchHeight = ref(0);

let rules = ref({
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
  coverUrl: [{ required: true, message: "请选择商品封面", trigger: "blur" }],
  type: [{ required: true, message: "请选择分类", trigger: "blur" }],
  intro: [{ required: true, message: "请输入课程介绍", trigger: "blur" }],
  courseDuration: [
    { required: true, message: "请输入总计课时", trigger: "blur" },
  ],
});

let tableMaxHeight = computed(() => {
  let hei =
    window.innerHeight - 84 - counter.pageHeight - 170 - searchHeight.value;
  return `${hei}px`;
});

onMounted(() => {
  onSubmit();
  getType();
  searchHeight.value = proxy.$refs.searchRef.offsetHeight;
});

function displayPrice_format(e) {
  let arr = [...e];
  let list = [];
  if (arr.length) {
    arr.forEach((element) => {
      if (element.discountPrice) list.push(element.discountPrice);
    });
  }
  list = ascendingSort(list);
  if (list.length) {
    if (list[0] == list[list.length - 1]) {
      return list[0];
    } else {
      return `${list[0]} - ${list[list.length - 1]}`;
    }
  } else {
    return null;
  }
}

async function getType() {
  courseType = await proxy.$apis.webCurriculum({
    type: "query",
  });
}

function ascendingSort(arr) {
  arr.sort((a, b) => a - b);
  return arr;
}

function type_format(arr) {
  let type = arr[0];
  let index = proxy.$utils.findIndexByField(courseType, "_id", type);
  if (index != -1) return courseType[index].name;
}

function inputSort(row) {
  let query = proxy.$utils.formatFunction(row, { ...model.value });
  if (proxy.$utils.isString(row.coverUrl)) {
    query.coverUrl = [row.coverUrl];
  }
  query._id = row._id;
  model.value = proxy.$utils.deepcopy(query);
  save();
}

function handleClose() {
  model.value = {
    name: "",
    price: "",
    coverUrl: [],
    contactQrCode: "", //联系二维码
    invoiceStart: null, //开票开始时间
    invoiceEnd: null, //开票结束时间
    intro: "", //富文本
    sort: 0,
    type: "", //分类
    lessonContent: [], //课程内容
    status: 1, //状态  //1 上架
    lessonContentMin: 1, //课时内容选择数量区间
    lessonContentMax: 1, //课时内容选择数量区间
    newPrice: null,
    courseDuration: null,
    consultingPhone: "", //咨询电话
    studentSource: "", //学员来源
    isEffective: 1, //是否有效
    navs: [],
    verifyRegistrations: 0, //是否校验报名次数
  };
  dialogVisible.value = false;
  showIntro.value = false;
  getInfo();
}

async function handleEdit(row, num) {
  switch (num) {
    case 1:
      let query = proxy.$utils.formatFunction(row, { ...model.value });
      if (proxy.$utils.isString(row.coverUrl)) {
        query.coverUrl = [row.coverUrl];
      }
      query._id = row._id;
      query.courseDuration = Number(row.courseDuration);
      model.value = proxy.$utils.deepcopy(query);
      dialogVisible.value = true;
      break;
    case 2:
      showIntro.value = true;
      model.value = proxy.$utils.formatFunction(row, { ...model.value });
      model.value._id = row._id;
      dialogVisible.value = true;
      break;
    case 3:
      let resp = await proxy.$utils.confirmTips(
        `是否确认${row.status === 1 ? "下架" : "上架"}该课程`
      );
      if (!resp) return;
      model.value = proxy.$utils.formatFunction(row, { ...model.value });
      model.value.status = model.value.status === 1 ? 0 : 1;
      model.value._id = row._id;
      await proxy.$apis.course({
        type: "update",
        data: model.value,
      });
      await getInfo();
      proxy.$utils.showToast(
        model.value.status === 1 ? "上架成功" : "下架成功"
      );
      break;
    case 4:
      let ret = await proxy.$utils.confirmTips("是否确认删除该课程");
      if (!ret) return;
      await proxy.$apis.course({
        type: "del",
        data: { _id: row._id },
      });
      getInfo();
      proxy.$utils.showToast("删除成功");
      break;
    case 5: //下载小程序码
      let result = await proxy.$apis.course({
        type: "getUnlimitedQRCode",
        data: { scene: row._id, name: row.name.trim() },
      });
      proxy.$utils.downloadBase64(result, `${row.name.trim()}.png`);
      break;
    case 6: //网站分享链接
      let url = `https://www.yacheng-edu.com/#/courseDetails?id=${row._id}`;
      proxy.$utils.copy(url);
      break;
    case 7: //网站分享二维码
      let link = `https://www.yacheng-edu.com/#/copyShareLink?id=${row._id}`;
      proxy.$refs.courseQrCodeRef.open(link);
      break;
    default:
      break;
  }
}

function onSubmit() {
  formInline.value.pageIndex = 1;
  getInfo();
}

async function getInfo() {
  try {
    tableLoading.value = true;
    tableParams.value = await proxy.$apis.course({
      data: formInline.value,
      type: "list",
    });
    console.log("列表", tableParams.value);
  } catch (error) {
  } finally {
    tableLoading.value = false;
  }
}

function init() {
  formInline.value = {
    pageIndex: 1,
    pageSize: 10,
    name: "",
    type: "",
    status: "",
  };
  getInfo();
}

async function handleSubmit() {
  if (!proxy.$refs.formRef) return;
  await proxy.$refs.formRef.validate((valid, fields) => {
    if (valid) {
      save();
    } else {
      console.log("error submit!", fields);
    }
  });
}

async function save() {
  try {
    loading.value = true;
    let data = proxy.$utils.deepcopy(model.value);
    let lessonContent = [...data.lessonContent];
    data.lessonContent = lessonContent.sort(proxy.$utils.compare("sort"));
    await proxy.$apis.course({
      type: model.value._id ? "update" : "add",
      data,
    });
    proxy.$utils.showToast("保存成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

watch(
  () => coverUrl.value,
  (newValue, oldValue) => {
    if (newValue) {
      model.value.coverUrl.push(newValue);
      setTimeout(() => {
        coverUrl.value = "";
      }, 100);
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => [formInline.value.name, formInline.value.type, formInline.value.status],
  (newValue, oldValue) => {
    if (newValue) onSubmit();
  },
  { deep: true, immediate: true }
);
</script>



<style lang="scss" scoped>
.container {
  .actionBtn {
    margin-bottom: 15px;
  }
  .bannerBox {
    width: 250px;
    border-radius: 10px;
    position: relative;
    margin-bottom: 10px;
    margin-right: 10px;
    .el-icon {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    img {
      width: 100%;
      display: block;
      border-radius: 10px;
      object-fit: cover;
    }
    .iconDel {
      position: absolute;
      right: 0;
      top: 0;
      background-color: #f44673;
      width: 15px;
      height: 15px;
      border-radius: 50%;
      cursor: pointer;
    }
  }
  .el-form {
    max-height: 70vh;
    overflow-y: auto;
  }
}
</style>






